<?php

namespace App\Services\Wechat;

use EasyWeChat\Factory;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class WechatJSSDKService
{
    protected $app;

    public function __construct()
    {
        $this->app = Factory::officialAccount(config('wechat.official_account.default'));
    }

    /**
     * 获取JS-SDK配置
     *
     * @param string $url 当前网页的URL，不包含#及其后面部分
     * @return array
     */
    public function getJsConfig(string $url): array
    {
        try {
            // 获取JS-SDK配置
            $app = $this->app;
            $app->jssdk->setUrl($url);
            
            // 获取配置
            $config = $app->jssdk->buildConfig([
                'updateAppMessageShareData', 
                'updateTimelineShareData',
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'chooseWXPay',
                'openLocation',
                'getLocation'
            ], false, false, false);

            return $config;
        } catch (\Exception $e) {
            Log::error('获取JS-SDK配置失败', [
                'url' => $url,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return [
                'appId' => '',
                'nonceStr' => '',
                'timestamp' => time(),
                'signature' => '',
                'jsApiList' => [],
                'error' => $e->getMessage()
            ];
        }
    }

    /**
     * 获取分享配置
     *
     * @param string $title 分享标题
     * @param string $desc 分享描述
     * @param string $link 分享链接
     * @param string $imgUrl 分享图标
     * @return array
     */
    public function getShareConfig(string $title, string $desc, string $link, string $imgUrl): array
    {
        return [
            'title' => $title,
            'desc' => $desc,
            'link' => $link,
            'imgUrl' => $imgUrl
        ];
    }
}